package api

import (
	"server/global"
	"server/model/request"
	"server/model/response"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type ImageApi struct{}

// ImageUpload 文件上传
// @Tags      文件路由
// @Summary   文件上传
// @Security  ApiKeyAuth
// @Description 文件上传
// @accept    multipart/form-data
// @Produce   application/json
// @Param     image formData   file   true "图片文件"
// @Success   200   {object}  response.ImageUpload{}
// @Router    /image/upload [post]
func (imageApi *ImageApi) ImageUpload(c *gin.Context) {
	_, header, err := c.Request.FormFile("image")
	if err != nil {
		global.Log.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}
	url, err := imageService.ImageUpload(header)
	if err != nil {
		global.Log.Error("Failed to upload image:", zap.Error(err))
		response.FailWithMessage("Failed to upload image", c)
		return
	}
	if global.Config.System.OssType == "qiniu" {
		url = global.Config.Qiniu.ImgPath + url
	}

	// local 返回格式 /uploads/image/fileName | qiniu 返回格式 http(s)://image.xxx.xx/fileName
	response.OkWithDetailed(response.ImageUpload{
		Url:     url,
		OssType: global.Config.System.OssType,
	}, "Successfully uploaded image", c)
}

// ImageDelete 文件删除
// @Tags      文件路由
// @Summary   文件删除
// @Description 文件删除
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.ImageDelete  true  "文件删除"
// @Success   200   {object}  string
// @Router    /image/delete [delete]
func (imageApi *ImageApi) ImageDelete(c *gin.Context) {
	var req request.ImageDelete
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err = imageService.ImageDelete(req)
	if err != nil {
		global.Log.Error("Failed to delete image:", zap.Error(err))
		response.FailWithMessage("Failed to delete image", c)
		return
	}
	response.OkWithMessage("Successfully deleted image", c)

}

// ImageList 获取文件列表信息
// @Tags      文件路由
// @Summary   获取文件列表信息
// @Description 获取文件列表信息
// @accept    application/json
// @Produce   application/json
// @Param     pageInfo  query    request.ImageList  true  "查询参数"
// @Success   200   {object}  response.PageResult  "获取文件列表信息成功"
// @Router    /image/list [get]
func (imageApi *ImageApi) ImageList(c *gin.Context) {
	var pageInfo request.ImageList
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	imageList, total, err := imageService.ImageList(pageInfo)
	if err != nil {
		global.Log.Error("Failed to get image list:", zap.Error(err))
		response.FailWithMessage("Failed to get image list", c)
		return
	}
	response.OkWithData(response.PageResult{
		List:  imageList,
		Total: total,
	}, c)
}
